<template>
<div>
    <van-nav-bar
  title="账号登录"
  left-arrow
  @click-left="onClickLeft"
/>
    <van-form @submit="onSubmit">
  <van-field
    v-model="username"
    name="username"
    placeholder="请输入账号"
    :rules="[{ required: true, message: '请填写用户名' },{ pattern:/\w{5,8}/, message: '长度为5到8位，只能出现数字、字母、下划线' }]"
  />
  <van-field
    v-model="password"
    type="password"
    name="password"
    placeholder="请输入密码"
    :rules="[{ required: true, message: '请填写密码' },{ pattern:/\w{5,12}/, message: '长度为5到12位，只能出现数字、字母、下划线' }]"
  />
  <div style="margin: 16px;">
    <van-button  block type="info" native-type="submit">登录</van-button>
  </div>
</van-form>
<div class="link"><router-link to="/register">还没有账号，去注册~</router-link></div>
</div>
</template>

<script>
import { login } from '@/api/user'
import { setToken } from '@/utils/storage'
export default {
  name: 'LoginIndex',
  data () {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    onClickLeft () {
      window.history.back()
    },
    async   onSubmit (values) {
      console.log('submit', values)
      const res = await login(values)
      console.log(res)
      if (res.data.status === 200) {
        this.$toast.success(res.data.description)
        this.username = ''
        this.password = ''
        setToken(res.data.body.token)
        setTimeout(() => {
          this.$router.push('/my')
        }, 300)
      } else {
        this.$toast.fail(res.data.description)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.link{
    display: flex;
    padding-top: 14px;
    justify-content: center;
    line-height: 1;
   a{
    color: #666;
    font-size: 12px;
    }
}
</style>
